package leetcode.easy;

/**
 * Created by hasee on 2017/5/25.
 */
public class ReverseWords_557 {
    public String reverseWords(String s) {
        String[] strArray = s.split(" ");
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<strArray.length;i++){
            sb.append(new StringBuilder(strArray[i]).reverse());
            if(i < strArray.length -1){
                sb.append(" ");
            }
        }
        return sb.toString();
    }

    private void reverse(char[] chars, int i, int j) {
        while (i < j) {
            char t = chars[i];
            chars[i++] = chars[j];
            chars[j--] = t;
        }
    }

    public String reverseWords2(String s) {
        if (s == null || s.length() == 0) {
            return s;
        }
        char[] chars = s.toCharArray();
        int start = 0;
        int len = s.length();
        while (start < len) {
            int space = s.indexOf(' ', start);
            space = space == -1 ? len : space;
            reverse(chars, start, space - 1);
            start = space + 1;
        }
        return String.valueOf(chars);
    }
}
